//
//  ViewController.m
//  25-GCD调研
//
//  Created by Snow on 16/8/17.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "ViewController.h"
#import "UIImageView+DownloadImage.h"
@interface ViewController ()
@property (nonatomic, strong) UIImageView *image;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /* 调研GCD, 明天会找同学分享(有想讲的也可以私聊我, 如果没有我就点名了)。
     总写代码会累, 适当研究些东西。
     调研需要提交的成果
     1.调研后的代码一份
     2.调研过程中所查阅的资料合集(格式任意)
     */
    
    //http://www.jianshu.com/p/c582d705f68e
    
    /* 1.GCD英文全称：Grand Central Dispatch 翻译就是 宏大的中央调度，是苹果开发的一种支持并行操作的机制,基于C语言，提供了非常多强大的函数
     */
    
    
    /* 2.Dispatch Queue是执行处理的等待队列 */
    //创建一个串行队列
    dispatch_queue_t serialQueue=dispatch_queue_create("com.serial.queue", DISPATCH_QUEUE_SERIAL);
    
    //创建一个并发队列
    dispatch_queue_t concurrentQueue=dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
    
    //第一个参数为队列名，第二个参数为队列类型，当然，第二个参数人如果写NULL，创建出来的也是一个串行队列。
    //系统准备的2个队列
    //(1)main dispatch queue 主线程
    dispatch_queue_t queue = dispatch_get_main_queue();
    //(2)global dispatch queues/根据优先级获取队列
    dispatch_queue_t queue1  = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    /* 3.执行队列中任务的两种方式，dispatch_sync是同步任务，dispatch_async是异步任务 */
    _image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    
    [self.view addSubview:_image];
    [self loadImage];
    [_image asynDownloadImageWithURL:@"http://pic1.win4000.com/wallpaper/8/511ce1c9ee276.jpg" completionHandler:^(NSData *data, UIImage *image) {
        
    }];
    [self createGCD];
}
//创建
- (void)createGCD
{
    //串行
    dispatch_queue_t queue = dispatch_queue_create("com.3g", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        [self snippet];
    });
    //并行
    dispatch_queue_t queue1 = dispatch_queue_create("com.4g", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue1, ^{
        [self snippet];
    });
}

//图片异步加载
- (void)loadImage
{
    //在子线程下载图片代码
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic1.win4000.com/wallpaper/8/511ce1c9ee276.jpg"]];
        //返回主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            _image.image = [UIImage imageWithData:data];
        });
    });
}
// 显示当前线程代码块
- (void)snippet{
    NSLog(@"thread - %@", [NSThread currentThread]);
    NSInteger sum = 0;
    for (NSInteger i = 0; i < 10000; i++) {
        sum += i;
    }
    NSLog(@"sum = %ld", sum);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
